import closePng from "@/assets/images/public/new-close-white.png";
import { Modal, ModalProps } from "@mantine/core";
import { useUpdateEffect } from "ahooks";
import classNames from "classnames";
import React from "react";

import { NImage } from "@/components/Uikit";

import { mergeClassNames } from "../tools";

export type NModalProps = ModalProps & {
  layout?: "blank";
  overlayBlur?: boolean;
  onOpen?: () => void;
  classNames?: {
    section?: string;
    article?: string;
  };
};

export const NModal: React.FC<NModalProps> = ({
  layout,
  overlayBlur,
  onOpen,
  title,
  withCloseButton = true,
  ...props
}) => {
  useUpdateEffect(() => {
    if (props.opened) {
      onOpen?.();
    }
  }, [props.opened]);
  const hasHeader = !!title;
  const blankLayout = layout === "blank";
  return (
    <Modal
      centered
      closeOnClickOutside={false}
      trapFocus={false}
      closeOnEscape={false}
      {...props}
      classNames={mergeClassNames(
        {
          overlay: overlayBlur ? "backdrop-blur-[5px] bg-black/50" : "bg-black/80",
          inner: "w-[375px]",
          content: "bg-transparent shadow-none",
          body: classNames({
            "p-10": !blankLayout,
            "p-0": blankLayout,
          }),
        },
        props.classNames,
      )}
      // transitionProps={{
      //   duration: 200,
      //   transition: 'pop',
      //   ...props.transitionProps,
      // }}
      radius={0}
      xOffset={0}
      yOffset={0}
      withCloseButton={false}
    >
      <div
        className={classNames({ "bg-bgc-6 rounded-6": !blankLayout }, props.classNames?.section)}
      >
        {hasHeader && (
          <header
            className={classNames(
              { "rounded-t-6 px-20": !blankLayout },
              "py-16 text-center",
              props.classNames?.header,
            )}
            style={props.styles?.header}
          >
            <div
              className={classNames("text-fcs-1 text-16 leading-20", props.classNames?.title)}
              style={props.styles?.title}
            >
              {title}
            </div>
          </header>
        )}
        <div
          className={classNames(
            { "px-10 pb-26": !blankLayout },
            { "pt-16": !hasHeader && !blankLayout },
            props.classNames?.article,
          )}
        >
          {props.children}
        </div>
      </div>
      {withCloseButton && (
        <NImage src={closePng} className='w-22 h-22 cursor-pointer' onClick={props.onClose} />
      )}
    </Modal>
  );
};
